

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Moe Wang">
  <meta name="keywords" content="">
  
    <meta name="description" content="变化侦测 什么是变化侦测？  Vue.js自动通过状态生成DOM，并将其输出到页面，此为渲染。Vue.js的渲染过程是声明式的，我们通过模版来描述状态与DOM之间的映射关系。而当应用内部状态变化时需要重新渲染，而如何确定状态中什么变化了就是变化侦测要解决的问题。 object的变化侦测如何追踪变化？两种方式可以追踪变化：Object.defineProperty和ES6的Proxy。 由于ES6在">
<meta property="og:type" content="article">
<meta property="og:title" content="w字总结《深入浅出Vue.js》之变化侦测篇">
<meta property="og:url" content="https://moewang0321.github.io/2021/12/06/w%E5%AD%97%E6%80%BB%E7%BB%93%E3%80%8A%E6%B7%B1%E5%85%A5%E6%B5%85%E5%87%BAVue.js%E3%80%8B%E4%B9%8B%E5%8F%98%E5%8C%96%E4%BE%A6%E6%B5%8B%E7%AF%87/index.html">
<meta property="og:site_name" content="moe_大杂烩">
<meta property="og:description" content="变化侦测 什么是变化侦测？  Vue.js自动通过状态生成DOM，并将其输出到页面，此为渲染。Vue.js的渲染过程是声明式的，我们通过模版来描述状态与DOM之间的映射关系。而当应用内部状态变化时需要重新渲染，而如何确定状态中什么变化了就是变化侦测要解决的问题。 object的变化侦测如何追踪变化？两种方式可以追踪变化：Object.defineProperty和ES6的Proxy。 由于ES6在">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-12-06T00:22:55.000Z">
<meta property="article:modified_time" content="2023-02-14T08:56:48.631Z">
<meta property="article:author" content="Moe Wang">
<meta property="article:tag" content="Vue.js">
<meta property="article:tag" content="读书笔记">
<meta name="twitter:card" content="summary_large_image">
  
  
  
  <title>w字总结《深入浅出Vue.js》之变化侦测篇 - moe_大杂烩</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"moewang0321.github.io","root":"/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>moe_大杂烩</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="w字总结《深入浅出Vue.js》之变化侦测篇"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2021-12-06 08:22" pubdate>
          2021年12月6日 早上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          18k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          148 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">w字总结《深入浅出Vue.js》之变化侦测篇</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="变化侦测"><a href="#变化侦测" class="headerlink" title="变化侦测"></a>变化侦测</h1><blockquote>
<p>什么是变化侦测？</p>
</blockquote>
<p>Vue.js自动通过状态生成DOM，并将其输出到页面，此为渲染。Vue.js的渲染过程是声明式的，我们通过模版来描述状态与DOM之间的映射关系。而当应用内部状态变化时需要重新渲染，而如何确定状态中什么变化了就是变化侦测要解决的问题。</p>
<h2 id="object的变化侦测"><a href="#object的变化侦测" class="headerlink" title="object的变化侦测"></a>object的变化侦测</h2><h3 id="如何追踪变化？"><a href="#如何追踪变化？" class="headerlink" title="如何追踪变化？"></a>如何追踪变化？</h3><p>两种方式可以追踪变化：<code>Object.defineProperty</code>和ES6的<code>Proxy</code>。</p>
<p>由于ES6在浏览器中的支持度不理想，所以Vue2采用了<code>Object.defineProperty</code>实现，而Vue3则采用了<code>Proxy</code>。</p>
<p>利用<code>Object.defineProperty</code>侦测对象变化可以写出这样的代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">defineReactiv</span> (data, key, val) &#123;<br>    <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperty</span>(data, key, &#123;<br>        <span class="hljs-attr">enumerable</span>: <span class="hljs-literal">true</span>,<br>        <span class="hljs-attr">configurable</span>: <span class="hljs-literal">true</span>,<br>        <span class="hljs-attr">get</span>: <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>            <span class="hljs-keyword">return</span> val<br>        &#125;,<br>        <span class="hljs-attr">set</span>: <span class="hljs-keyword">function</span> (<span class="hljs-params">newVal</span>) &#123;<br>            <span class="hljs-keyword">if</span>(val === newVal) &#123;<br>                <span class="hljs-keyword">return</span><br>            &#125;<br>            val = newVal<br>        &#125;<br>    &#125;)<br>&#125;<br></code></pre></td></tr></table></figure>
<p>defineReactive是对Object.defineProperty的封装，其作用为定义一个响应式数据，在这个函数中进行变化追踪，封装后只需要传递data，key，value即可。封装好后，每当从data的key中读取数据，get函数被触发；往data的key中设置数据时，set函数被触发。</p>
<h3 id="如何收集依赖？收集在哪里？"><a href="#如何收集依赖？收集在哪里？" class="headerlink" title="如何收集依赖？收集在哪里？"></a>如何收集依赖？收集在哪里？</h3><blockquote>
<p>在Vue2中，模板使用数据等同于组件使用数据，所以数据变化时，会将通知发送到组件，组件内部再通过虚拟DOM重新渲染。</p>
</blockquote>
<p>我们观察依赖的目的是当数据发生变化的时候，通知那些使用了该数据的地方。所以我们需要收集依赖，把用到数据的地方收集起来，等属性发生变化时，将之前收集好的依赖循环触发一遍，也就是在getter中收集依赖，setter中触发依赖。</p>
<p>现在已经知道了要在哪里收集触发依赖，那么要把它收集到哪里？我们创建一个专门帮助管理依赖的类Dep，使用这个类，我们可以收集、删除依赖或向依赖发送通知。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Dep</span> &#123;<br>    <span class="hljs-title function_">constructor</span>(<span class="hljs-params"></span>) &#123;<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">subs</span> = []<br>    &#125;<br>    <br>    <span class="hljs-title function_">addSub</span>(<span class="hljs-params">sub</span>) &#123;<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">subs</span>.<span class="hljs-title function_">push</span>(sub)<br>    &#125;<br>    <br>    <span class="hljs-title function_">removeSub</span>(<span class="hljs-params">sub</span>) &#123;<br>        <span class="hljs-title function_">remove</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">subs</span>, sub)<br>    &#125;<br>    <span class="hljs-title function_">depend</span>(<span class="hljs-params"></span>) &#123;<br>        <span class="hljs-keyword">if</span>(<span class="hljs-variable language_">window</span>.<span class="hljs-property">target</span>) &#123;<br>            <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addSub</span>(windwo.<span class="hljs-property">target</span>)<br>        &#125;<br>    &#125;<br>    <br>    <span class="hljs-title function_">notify</span>(<span class="hljs-params"></span>) &#123;<br>        <span class="hljs-keyword">const</span> subs = <span class="hljs-variable language_">this</span>.<span class="hljs-property">subs</span>.<span class="hljs-title function_">slice</span>()<br>        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>, l = subs.<span class="hljs-property">length</span>; i &lt; l; i++) &#123;<br>            subs[i].<span class="hljs-title function_">update</span>()<br>        &#125;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">remove</span> (arr, item) &#123;<br>    <span class="hljs-keyword">if</span> (arr.<span class="hljs-property">length</span>) &#123;<br>        <span class="hljs-keyword">const</span> index = arr.<span class="hljs-title function_">indexOf</span>(item)<br>        <span class="hljs-keyword">if</span>(index &gt; -<span class="hljs-number">1</span>) &#123;<br>            <span class="hljs-keyword">return</span> arr.<span class="hljs-title function_">splice</span>(index, <span class="hljs-number">1</span>)<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>再改造一下defineReactive</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">defineReactive</span> (data, key, val) &#123;<br>    <span class="hljs-keyword">let</span> dep = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Dep</span>()<br>    <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperty</span>(data, key, &#123;<br>        <span class="hljs-attr">enumerable</span>: <span class="hljs-literal">true</span>,<br>        <span class="hljs-attr">configurable</span>: <span class="hljs-literal">true</span>,<br>        <span class="hljs-attr">get</span>: <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>            dep.<span class="hljs-title function_">depend</span>()<br>            <span class="hljs-keyword">return</span> val<br>        &#125;,<br>        <span class="hljs-attr">set</span>: <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>            <span class="hljs-keyword">if</span>(val === newVal) &#123;<br>               <span class="hljs-keyword">return</span> <br>            &#125;<br>            val = newVal<br>            dep.<span class="hljs-title function_">notify</span>()<br>        &#125;<br>    &#125;)<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="什么是Watcher"><a href="#什么是Watcher" class="headerlink" title="什么是Watcher"></a>什么是Watcher</h3><p>上边的代码中，我们收集的依赖是window.target，那我们究竟要收集谁呢。收集说的通俗易懂点就是当属性变化时，我们应该通知谁。</p>
<p>我们需要通知用到数据的地方，而用到它的地方可能会很多，有可能是模版，也有可能是watch等等，所以我们需要抽象出一个能集中处理这些情况的类。我们在收集依赖阶段只收集这个封装好的类实例，同样也只通知它自己，由它负责通知其他地方，这就是Watcher。</p>
<p>Watcher是一个中介的角色，数据变化时通知它，他负责通知其他地方。</p>
<p>首先看一下Watcher的经典使用方式：当a.b.c变化时会触发第二个参数中的函数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js">vm.$watch(<span class="hljs-string">&#x27;a.b.c&#x27;</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params">newVal, oldVal</span>) &#123;<br>    <span class="hljs-comment">// 操作</span><br>&#125;)<br></code></pre></td></tr></table></figure>

<p>根据使用方法我们可以首先实现Watcher：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Watcher</span> &#123;<br>    <span class="hljs-title function_">constructor</span>(<span class="hljs-params">vm, expOrFn, cb</span>) &#123;<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">vm</span> = vm<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">getter</span> = <span class="hljs-title function_">parsePath</span>(expOrFn)<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">cb</span> = cb<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> = <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">get</span>()<br>    &#125;<br>    <br>    <span class="hljs-title function_">get</span>(<span class="hljs-params"></span>) &#123;<br>        <span class="hljs-variable language_">window</span>.<span class="hljs-property">target</span> = <span class="hljs-variable language_">this</span><br>        <span class="hljs-keyword">let</span> value = <span class="hljs-variable language_">this</span>.<span class="hljs-property">getter</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">vm</span>, <span class="hljs-variable language_">this</span>.<span class="hljs-property">vm</span>)<br>        windwo.<span class="hljs-property">target</span> = <span class="hljs-literal">undefined</span><br>        <span class="hljs-keyword">return</span> value<br>    &#125;<br>    <br>    <span class="hljs-title function_">update</span>(<span class="hljs-params"></span>) &#123;<br>        <span class="hljs-keyword">const</span> oldValue = <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span><br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> = <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">get</span>()<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">cb</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">vm</span>, <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span>, oldValue)<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>这段胆码可以把自己主动添加到data.a.b.c的Dep中。在get方法中先把window.target设置为this即当前的watcher实例，然后读data.a.b.c的值，触发getter。</p>
<p>触发了getter，就会触发收集依赖的逻辑，从window.target中读取一个依赖添加到Dep中。这样只要在window.target赋一个this，再读一下值，触发getter，就可以把this主动添加到keypath的Dep中。</p>
<p>依赖注入到Dep中后，每次值变化就会让依赖列表中所有依赖循环触发update方法，执行参数中的回调函数，将value和oldValue传到参数中。</p>
<h3 id="递归侦测所有key"><a href="#递归侦测所有key" class="headerlink" title="递归侦测所有key"></a>递归侦测所有key</h3><p>现在已经可以实现变化侦测的功能，但是我们希望把数据中所有属性（含子属性）都侦测到，需要一个Observer类。它的作用是将一个数据内所有属性都转换成getter/setter形式，再去追踪他们的变化</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Observer</span> &#123;<br>    <span class="hljs-title function_">constructor</span>(<span class="hljs-params">value</span>) &#123;<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> = value<br>        <br>        <span class="hljs-keyword">if</span>(!<span class="hljs-title class_">Array</span>.<span class="hljs-title function_">isArray</span>(value)) &#123;<br>            <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">walk</span>(value)<br>        &#125;<br>    &#125;<br>    <br>    <span class="hljs-title function_">walk</span>(<span class="hljs-params"></span>) &#123;<br>        <span class="hljs-keyword">const</span> keys = <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">keys</span>(obj)<br>        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; keys.<span class="hljs-property">length</span>; i++) &#123;<br>            <span class="hljs-title function_">defineReactive</span>(obj, keys[i], obj[keys[i]])<br>        &#125;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">defineReactive</span>(<span class="hljs-params">data, key, val</span>) &#123;<br>    <span class="hljs-keyword">if</span>(<span class="hljs-keyword">typeof</span> val === <span class="hljs-string">&#x27;object&#x27;</span>) &#123;<br>        <span class="hljs-keyword">new</span> <span class="hljs-title class_">Observer</span>(val)<br>    &#125;<br>    <br>    <span class="hljs-keyword">let</span> dep = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Dep</span>()<br>    <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperty</span>(data, key, &#123;<br>    <span class="hljs-attr">enumerable</span>: <span class="hljs-literal">true</span>,<br>    <span class="hljs-attr">configurable</span>: <span class="hljs-literal">true</span>,<br>    <span class="hljs-attr">get</span>: <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>        dep.<span class="hljs-title function_">depend</span>()<br>        <span class="hljs-keyword">return</span> val<br>    &#125;,<br>    <span class="hljs-attr">set</span>: <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>        <span class="hljs-keyword">if</span>(val === newVal) &#123;<br>           <span class="hljs-keyword">return</span> <br>        &#125;<br>        val = newVal<br>        dep.<span class="hljs-title function_">notify</span>()<br>        &#125;<br>    &#125;)<br>&#125;<br></code></pre></td></tr></table></figure>

<p>我们定义Observer类，将正常对象转换成被侦测的对象。然后判断数据类型，只有Object才会调用walk进行转换，最后在defineReactive中新增<code>new Observer(val)</code>来递归子属性。</p>
<h3 id="关于Object的问题"><a href="#关于Object的问题" class="headerlink" title="关于Object的问题"></a>关于Object的问题</h3><p>上边我们介绍了Object类型的变化侦测原理，正是因为数据变化是通过getter/setter进行追踪，所以有些语法中即使数据变化，Vue也追踪不到。</p>
<p>比如，向object添加或删除属性：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> vm = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Vue</span>(&#123;<br>    <span class="hljs-attr">el</span>:<span class="hljs-string">&#x27;#app&#x27;</span>,<br>    <span class="hljs-attr">template</span>:<span class="hljs-string">&#x27;#demo-template&#x27;</span>,<br>    <span class="hljs-attr">methods</span>:&#123;<br>        <span class="hljs-title function_">action</span>(<span class="hljs-params"></span>) &#123;<br>            <span class="hljs-variable language_">this</span>.<span class="hljs-property">obj</span>.<span class="hljs-property">age</span> = <span class="hljs-string">&#x27;23&#x27;</span><br>        &#125;,<br>        <span class="hljs-title function_">dAction</span>(<span class="hljs-params"></span>) &#123;<br>            <span class="hljs-keyword">delete</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">obj</span>.<span class="hljs-property">name</span><br>        &#125;<br>    &#125;,<br>    <span class="hljs-attr">data</span>: &#123;<br>        <span class="hljs-attr">obj</span>:&#123;<br>            <span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;abc&#x27;</span><br>        &#125;<br>    &#125;<br>&#125;)<br></code></pre></td></tr></table></figure>

<p>Object.defineProperty将对象的key转化为getter/setter来追踪变化，但它只能追踪一个数据是否被修改，无法侦测新增和删除。</p>
<p>所以Vue提供两个API：vm.$set和vm.$delete</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>Object可以通过Object.defineProperty将属性转换成getter/setter形式来追踪变化，读取触发getter，修改触发setter。</p>
<p>在getter中对使用了数据的依赖进行收集，当setter触发时通知getter中收集的依赖数据发生变化。</p>
<p>收集依赖需要为依赖找一个储存的地方，所以有了Dep，它用来收集、删除依赖并向依赖发送消息。</p>
<p>依赖就是Watcher，只有Watcher触发的getter才会收集依赖，哪个Watcher触发了getter就把它收集到Dep中，数据发生变化时会循环依赖列表通知所有Watcher。</p>
<p>Watcher的原理是先把自己设置到全局唯一的位置，然后读取数据触发getter，接着getter中就会从唯一的位置读取当前正在读取数据的Watcher，并把它收集到Dep中，这样Watcher可以主动去订阅任一数据的变化。</p>
<p>此外，还创建了Observer类，它是用来将一个object中的所有数据（包括子数据）都转换成响应式的。</p>
<h2 id="Array的变化侦测"><a href="#Array的变化侦测" class="headerlink" title="Array的变化侦测"></a>Array的变化侦测</h2><p>Array的侦测为什么与Object不同，因为Object使用getter/setter侦测变化，而数组通常使用push等方法来改变，不会触发getter/setter。</p>
<h3 id="如何追踪变化"><a href="#如何追踪变化" class="headerlink" title="如何追踪变化"></a>如何追踪变化</h3><p>这里不讨论ES6的情况，在ES6以前，我们没有能够拦截原型方法（push等）的能力，但我们可以用自定义方法覆盖原生的原型方法。</p>
<p>我们可以用一个拦截器覆盖Array.prototype。之后每当使用原型上的方法操作数组的时候，执行的其实是拦截器中的方法，之后在拦截器内使用原生的原型方法去操作数组。</p>
<h3 id="拦截器"><a href="#拦截器" class="headerlink" title="拦截器"></a>拦截器</h3><p>数组原型上的方法有七个，分别是push，pop，shift，unshift，splice，sort和reverse。我们可以实现一个和原型样的Object，里面的属性一模一样，只不过其中改变数组自身内容的方法是重写的。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> arrayProto = <span class="hljs-title class_">Array</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span><br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> arrayMethods = <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">create</span>(arrayProto)<br><br><span class="hljs-keyword">const</span> methods = [<span class="hljs-string">&#x27;push&#x27;</span>,<span class="hljs-string">&#x27;pop&#x27;</span>,<span class="hljs-string">&#x27;shift&#x27;</span>,<span class="hljs-string">&#x27;unshift&#x27;</span>,<span class="hljs-string">&#x27;splice&#x27;</span>,<span class="hljs-string">&#x27;sort&#x27;</span>,<span class="hljs-string">&#x27;reverse&#x27;</span>]<br><br>methods.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">method</span>) =&gt;</span> &#123;<br>    <span class="hljs-keyword">const</span> original = arrayProto[method]<br>    <br>    <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperty</span>(arrayMethods , method , &#123;<br>        <span class="hljs-attr">value</span>: <span class="hljs-keyword">function</span> <span class="hljs-title function_">mutator</span>(<span class="hljs-params">...args</span>) &#123;<br>            <span class="hljs-keyword">return</span> original.<span class="hljs-title function_">apply</span>(<span class="hljs-variable language_">this</span>, args)<br>        &#125;,<br>        <span class="hljs-attr">enumerable</span>:<span class="hljs-literal">false</span>,<br>        <span class="hljs-attr">writable</span>: <span class="hljs-literal">true</span>,<br>        <span class="hljs-attr">configurable</span>:<span class="hljs-literal">true</span><br>    &#125;)<br>&#125;)<br></code></pre></td></tr></table></figure>
<p>创建了arrayMethods继承自Array.prototype，具备所有功能，接下来使用Object.defineProperty对改变数组的方法进行封装。所以当我们调用push的时候，实际调用的是arrayMethods.push，而它实际上是mutator函数，在mutator函数中执行original（原生方法）来做应该做的事，我们可以在mutator中做其他的事比如发送变化通知。</p>
<h3 id="使用拦截器覆盖Array原型"><a href="#使用拦截器覆盖Array原型" class="headerlink" title="使用拦截器覆盖Array原型"></a>使用拦截器覆盖Array原型</h3><p>我们需要用它覆盖Array.prototype，但又不能直接覆盖，因为这样会污染全局的Array。我们希望拦截只针对那些被侦测了变化的数据生效，也就是希望拦截器只覆盖那些响应式数组的原型。</p>
<p>而数据转成响应式的，需要通过Observer，所以我们只需要在Observer中用拦截器覆盖那些Array类型数据的原型。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Observer</span> &#123;<br>    <span class="hljs-title function_">constructor</span>(<span class="hljs-params">value</span>) &#123;<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> = value<br>        <br>        <span class="hljs-keyword">if</span>(<span class="hljs-title class_">Array</span>.<span class="hljs-title function_">isArray</span>(value)) &#123;<br>            value.<span class="hljs-property">_proto_</span> = arrayMethods<br>        &#125; <span class="hljs-keyword">else</span> &#123;<br>            <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">walk</span>(value)<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>它的作用是将拦截器赋给value._proto_，覆盖value原型的功能。</p>
<h3 id="拦截器挂载到数组属性上"><a href="#拦截器挂载到数组属性上" class="headerlink" title="拦截器挂载到数组属性上"></a>拦截器挂载到数组属性上</h3><p>部分浏览器可能不支持_proto_，而Vue的做法是如果不能使用_proto_，则直接将arrayMethods身上的方法设置到被侦测的数组上：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> hasProto = <span class="hljs-string">&#x27;_proto_&#x27;</span> <span class="hljs-keyword">in</span> &#123;&#125;<br><br><span class="hljs-keyword">const</span> arrayKeys = <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">getOwnPropertyNames</span>(arrayMethods)<br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Observer</span> &#123;<br>    <span class="hljs-title function_">constructor</span>(<span class="hljs-params">value</span>) &#123;<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> = value<br>        <br>        <span class="hljs-keyword">if</span>(<span class="hljs-title class_">Array</span>.<span class="hljs-title function_">isArray</span>(value)) &#123;<br>            <span class="hljs-keyword">const</span> augment = hasProto ? protoAugment : copyAugment<br>            <br>            <span class="hljs-title function_">augment</span>(value, arrayMethods, arrayKeys)<br>        &#125; <span class="hljs-keyword">else</span> &#123;<br>            ...<br>        &#125;<br>    &#125;<br>    <br>    ...<br>&#125;<br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">protoAugment</span>(<span class="hljs-params">target, src, keys</span>) &#123;<br>    target.<span class="hljs-property">_proto_</span> = src<br>&#125;<br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">copyAugment</span>(<span class="hljs-params">target, src, keys</span>) &#123;<br>    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>,l = keys.<span class="hljs-property">length</span>;i &lt; l; i++) &#123;<br>        <span class="hljs-keyword">const</span> key = keys[i]<br>        <span class="hljs-title function_">def</span>(target, key, src[key])<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="如何收集依赖"><a href="#如何收集依赖" class="headerlink" title="如何收集依赖"></a>如何收集依赖</h3><p>我们已完成了拦截器，本质上是为了当数组内容变化时能够得到通知Dep中的依赖的能力。而数组也是在getter中收集依赖的。想要读取数组，首先肯定会触发这个数组的名对应属性的getter。而Array的依赖和Object一样，也会在defineReactive中收集：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">defineReactive</span>(<span class="hljs-params">data, key, val</span>) &#123;<br>    <span class="hljs-keyword">if</span>(<span class="hljs-keyword">typeof</span> val === <span class="hljs-string">&#x27;object&#x27;</span>) <span class="hljs-keyword">new</span> <span class="hljs-title class_">Observer</span>(val)<br>    <br>    <span class="hljs-keyword">let</span> dep = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Dep</span>()<br>    <br>    <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">deintProperty</span>(data,key, &#123;<br>        <span class="hljs-attr">enumerable</span>:<span class="hljs-literal">true</span>,<br>        <span class="hljs-attr">configurable</span>:<span class="hljs-literal">true</span>,<br>        <span class="hljs-attr">get</span>:<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) &#123;<br>            dep.<span class="hljs-title function_">depend</span>()<br>            <span class="hljs-comment">// 收集数组的依赖</span><br>            <br>            <span class="hljs-keyword">return</span> val<br>        &#125;,<br>        <span class="hljs-attr">set</span>:<span class="hljs-keyword">function</span>(<span class="hljs-params">newVal</span>) &#123;<br>            <span class="hljs-keyword">if</span>(val === newVal) <span class="hljs-keyword">return</span><br>            <br>            dep.<span class="hljs-title function_">notify</span>()<br>            val = newVal<br>        &#125;<br>    &#125;)<br>&#125;<br></code></pre></td></tr></table></figure>

<p>Array在getter中收集依赖，在拦截器中触发依赖。</p>
<h3 id="依赖列表存在哪"><a href="#依赖列表存在哪" class="headerlink" title="依赖列表存在哪"></a>依赖列表存在哪</h3><p>Array的依赖被存放在Observer中：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Observer</span> &#123;<br>    <span class="hljs-title function_">constructor</span>(<span class="hljs-params">value</span>) &#123;<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> = value<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">dep</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Dep</span>() <span class="hljs-comment">// 新增dep</span><br>        <br>        <span class="hljs-keyword">if</span>(<span class="hljs-title class_">Array</span>.<span class="hljs-title function_">isArray</span>(value)) &#123;<br>            <span class="hljs-keyword">const</span> augment = hasProto ? protoAugment : copyAugment<br>            <br>            <span class="hljs-title function_">augment</span>(value, arrayMethods, arrayKeys)<br>        &#125; <span class="hljs-keyword">else</span> &#123;<br>            ...<br>        &#125;<br>    &#125;<br>    <br>    ...<br>&#125;<br><br></code></pre></td></tr></table></figure>

<p>我们有个疑问，为什么数组的dep要保存在Observer实例上呢。因为数组在getter中收集依赖，在拦截器中触发依赖，所以依赖保存的位置很关键，需要在getter和拦截器中都能访问到。将Dep实例保存到Observer的属性上以后，我们能够在getter中访问并收集。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">defineReactive</span>(<span class="hljs-params">data, key, val</span>) &#123;<br>    <span class="hljs-keyword">let</span> childOb = <span class="hljs-title function_">observer</span>(val)<br>    <span class="hljs-keyword">let</span> dep = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Dep</span>()<br>    <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProerty</span>(data, key, &#123;<br>        <span class="hljs-attr">enumerable</span>:<span class="hljs-literal">true</span>,<br>        <span class="hljs-attr">configurable</span>:<span class="hljs-literal">true</span>,<br>        <span class="hljs-attr">get</span>:<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) &#123;<br>            dep.<span class="hljs-title function_">depend</span>()<br>            <span class="hljs-keyword">if</span>(childOb) &#123;<br>                childOb.<span class="hljs-property">dep</span>.<span class="hljs-title function_">depend</span>()<br>            &#125;<br>            <span class="hljs-keyword">return</span> val<br>        &#125;,<br>        <span class="hljs-attr">set</span>:<span class="hljs-keyword">function</span>(<span class="hljs-params">newVal</span>) &#123;<br>            <span class="hljs-keyword">if</span>(val === newVal) &#123;<br>                <span class="hljs-keyword">return</span><br>            &#125;<br>            <br>            dep.<span class="hljs-title function_">notify</span>()<br>            val = newVal<br>        &#125;<br>    &#125;)<br>&#125;<br></code></pre></td></tr></table></figure>

<p>在defineReactive中调用observe，将val当做参数传进去拿到返回值，就是observer实例。</p>
<h3 id="在拦截器中获取Observer实例"><a href="#在拦截器中获取Observer实例" class="headerlink" title="在拦截器中获取Observer实例"></a>在拦截器中获取Observer实例</h3><p>因为Array拦截器是对原型的一种封装，所以在拦截器中可以访问到this。而dep保存在Observer中，所以需要在this上读到Observer实例。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">def</span> (obj, key, val, enumerable) &#123;<br>    <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperty</span>(obj, key,  &#123;<br>        <span class="hljs-attr">value</span>:val,<br>        <span class="hljs-attr">enumerable</span>:!!enumerable,<br>        <span class="hljs-attr">writable</span>:<span class="hljs-literal">true</span>,<br>        <span class="hljs-attr">configruable</span>:<span class="hljs-literal">true</span><br>    &#125;)<br>&#125;<br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Observer</span> &#123;<br>    <span class="hljs-title function_">constructor</span>(<span class="hljs-params">value</span>) &#123;<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> = value<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">dep</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Dep</span>()<br>        <br>        <span class="hljs-title function_">def</span>(value , <span class="hljs-string">&#x27;__ob__&#x27;</span>,<span class="hljs-variable language_">this</span>)<br>        <br>        <span class="hljs-keyword">if</span>(<span class="hljs-title class_">Array</span>.<span class="hljs-title function_">isArray</span>(value)) &#123;<br>            ...<br>        &#125; <span class="hljs-keyword">else</span> &#123;<br>            ...<br>        &#125;<br>    &#125;<br>    ...<br>&#125;<br></code></pre></td></tr></table></figure>

<p>上述代码在Observer中新增了一段代码，它在value上新增了一个不可枚举的__ob__属性即当前Observer实例。它还可以用来标记当前value是否被Observer转换成响应式数据。</p>
<p>也就是说所有被侦测了的数据身上都会有一个__ob__来表示它们是响应式的，可以通过value.__ob__来访问Observer实例。如果是Array拦截器，因为它是原型方法，所以可以直接通过this.__ob__来访问Observer实例。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs js"><br>[<span class="hljs-string">&#x27;push&#x27;</span>,<span class="hljs-string">&#x27;pop&#x27;</span>,……].<span class="hljs-title function_">forEach</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params">method</span>) &#123;<br>    <span class="hljs-keyword">const</span> original = arrayProto[method]<br>    <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperty</span>(arrayMethods,method, &#123;<br>        <span class="hljs-attr">value</span>:<span class="hljs-keyword">function</span> <span class="hljs-title function_">mutator</span>(<span class="hljs-params">...args</span>) &#123;<br>            <span class="hljs-keyword">const</span> ob = <span class="hljs-variable language_">this</span>.<span class="hljs-property">__ob__</span><br>            <span class="hljs-keyword">return</span> original.<span class="hljs-title function_">apply</span>(<span class="hljs-variable language_">this</span>,args)<br>        &#125;,<br>        ...<br>    &#125;)<br>&#125;)<br><br></code></pre></td></tr></table></figure>

<h3 id="向数组依赖发送通知"><a href="#向数组依赖发送通知" class="headerlink" title="向数组依赖发送通知"></a>向数组依赖发送通知</h3><p>我们只需要在拦截器中访问Observer实例，拿到dep属性，直接发送通知即可。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs js"><br>[<span class="hljs-string">&#x27;push&#x27;</span>,<span class="hljs-string">&#x27;pop&#x27;</span>,……].<span class="hljs-title function_">forEach</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params">method</span>) &#123;<br>    <span class="hljs-keyword">const</span> original = arrayProto[method]<br>    <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperty</span>(arrayMethods,method, &#123;<br>        <span class="hljs-attr">value</span>:<span class="hljs-keyword">function</span> <span class="hljs-title function_">mutator</span>(<span class="hljs-params">...args</span>) &#123;<br>            <span class="hljs-keyword">const</span> ob = <span class="hljs-variable language_">this</span>.<span class="hljs-property">__ob__</span><br>            ob.<span class="hljs-property">dep</span>.<span class="hljs-title function_">notify</span>()<br>            <span class="hljs-keyword">return</span> original.<span class="hljs-title function_">apply</span>(<span class="hljs-variable language_">this</span>,args)<br>        &#125;,<br>        ...<br>    &#125;)<br>&#125;)<br><br></code></pre></td></tr></table></figure>

<h3 id="侦测数组元素变化及新增变化"><a href="#侦测数组元素变化及新增变化" class="headerlink" title="侦测数组元素变化及新增变化"></a>侦测数组元素变化及新增变化</h3><h4 id="元素变化"><a href="#元素变化" class="headerlink" title="元素变化"></a>元素变化</h4><p>介绍Observer时说过，作用是将object的属性变为getter/setter形式，现在Observer类不仅处理Object类型，还要处理Array类型。所以我们要在Observer中新增一些处理，让它能把Array也变成响应式：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Observer</span> &#123;<br>    <span class="hljs-title function_">constructor</span>(<span class="hljs-params">value</span>) &#123;<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> = value<br>        <span class="hljs-title function_">def</span>(value,<span class="hljs-string">&#x27;__ob__&#x27;</span>,<span class="hljs-variable language_">this</span>)<br>        <span class="hljs-keyword">if</span>(<span class="hljs-title class_">Array</span>.<span class="hljs-title function_">isArray</span>(value)) &#123;<br>            <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">observeArray</span>(value)<br>        &#125; <span class="hljs-keyword">else</span> &#123;<br>            <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">walk</span>(value)<br>        &#125;<br>    &#125;<br>    <br>    ...<br>    <br>    <span class="hljs-title function_">observeArray</span>(<span class="hljs-params">items</span>) &#123;<br>        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>,l = items.<span class="hljs-property">length</span>;i &lt; l; i++) &#123;<br>            <span class="hljs-title function_">observe</span>(items[i])<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="新增元素的变化"><a href="#新增元素的变化" class="headerlink" title="新增元素的变化"></a>新增元素的变化</h4><ol>
<li>获取新增元素</li>
</ol>
<p>我们需要在拦截器中队数组方法的类型进行判断，如果是push、unshift和splice（添加元素方法），需要把参数中新增的元素拿过来，用Observer侦测。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs js">[<span class="hljs-string">&#x27;push&#x27;</span>,<span class="hljs-string">&#x27;pop&#x27;</span>,……].<span class="hljs-title function_">forEach</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params">method</span>) &#123;<br>    <span class="hljs-keyword">const</span> original = arrayProto[method]<br>    <span class="hljs-title function_">def</span>(arrayMethods, method, <span class="hljs-keyword">function</span> <span class="hljs-title function_">mutator</span>(<span class="hljs-params">...args</span>) &#123;<br>        <span class="hljs-keyword">const</span> result = original.<span class="hljs-title function_">apply</span>(<span class="hljs-variable language_">this</span>, args)<br>        <span class="hljs-keyword">const</span> ob = <span class="hljs-variable language_">this</span>.<span class="hljs-property">__ob__</span><br>        <span class="hljs-keyword">let</span> inserted<br>        <span class="hljs-keyword">switch</span>(method) &#123;<br>            <span class="hljs-keyword">case</span> <span class="hljs-string">&#x27;push&#x27;</span>:<br>            <span class="hljs-keyword">case</span> <span class="hljs-string">&#x27;unshift&#x27;</span>:<br>                inserted = args<br>                <span class="hljs-keyword">break</span><br>            <span class="hljs-keyword">case</span> <span class="hljs-string">&#x27;splice&#x27;</span>:<br>                inserted = args.<span class="hljs-title function_">slice</span>(<span class="hljs-number">2</span>)<br>                <span class="hljs-keyword">break</span><br>        &#125;<br>        ob.<span class="hljs-property">dep</span>.<span class="hljs-title function_">notify</span>()<br>        <span class="hljs-keyword">return</span> result<br>    &#125;)<br>&#125;)<br></code></pre></td></tr></table></figure>

<h3 id="关于数组的问题"><a href="#关于数组的问题" class="headerlink" title="关于数组的问题"></a>关于数组的问题</h3><p>对Array的变化侦测是通过拦截原型的方法实现，所以有些操作Vue无法拦截，比如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-variable language_">this</span>.<span class="hljs-property">list</span>[<span class="hljs-number">0</span>] = <span class="hljs-number">2</span><br><span class="hljs-variable language_">this</span>.<span class="hljs-property">list</span>.<span class="hljs-property">length</span> = <span class="hljs-number">0</span><br></code></pre></td></tr></table></figure>

<p>无法侦测数组变化，不会触发re-render或者watch。</p>
<h3 id="总结-1"><a href="#总结-1" class="headerlink" title="总结"></a>总结</h3><p>Array的追踪方式和Object不同，因为它是通过方法来改变内容，所以通过创建拦截器去覆盖数组的原型方法来追踪变化。</p>
<p>而为了不污染全局的原型方法，我们在Observer中只针对需要侦测变化的数组用__proto__来覆盖原型方法，而ES6之前并不是所有浏览器都支持，所以针对不支持的浏览器，我们循环拦截器，将方法设置到数组身上来拦截Array.prototype上的原型方法。</p>
<p>Array同Object收集依赖的方式相同，均在getter中，但是使用依赖的位置不同，数组要在拦截器中向依赖发送消息，所以依赖不能像Object一样保存在defineReactive中，而是保存在Observer实例上。</p>
<p>在Observer中队每个侦测了变化的数据都标记__ob__，并把this保存在__ob__上。主要有两个作用，一方面为了标记数据是否被侦测变化（保证同一数据只侦测一次），另一方面可以很方便的通过数据取到__ob__，从而拿到Observer上保存的依赖，发送通知。</p>
<p>除了侦测数组自身变化，数组中元素的变化也要侦测，在Observer中判断如果当前被侦测数据是数组，则调用observerArray将数组中每个元素转换成响应式。</p>
<p>除了已有数据的侦测，当使用push等方法新增数据时，新增的数据也要侦测，我们使用当前操作数组的方法判断，如果是push、unshift和splice，则将参数中的新增数据提取出来，对其转换。</p>
<h2 id="变化侦测相关的api实现原理"><a href="#变化侦测相关的api实现原理" class="headerlink" title="变化侦测相关的api实现原理"></a>变化侦测相关的api实现原理</h2><h3 id="vm-watch"><a href="#vm-watch" class="headerlink" title="vm.$watch"></a>vm.$watch</h3><h4 id="用法"><a href="#用法" class="headerlink" title="用法"></a>用法</h4><p><code>vm.$watch(expOfFn, callback, [options])</code></p>
<p>用于观察一个表达式或computed函数在vue实例上的变化。回调函数调用时会从参数得到新数据和旧数据，表达式只接受以点分隔的路径，例如<code>a.b.c</code>。</p>
<p>options包括deep和immediate，deep为了发现对象内部值的变化，immediate将立即以表达式的当前值触发回调。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js">vm.$watch(<span class="hljs-string">&#x27;someObject&#x27;</span>,callback, &#123;<br>    <span class="hljs-attr">deep</span>:<span class="hljs-literal">true</span>, <span class="hljs-comment">// someObject.a修改时触发。</span><br>    <span class="hljs-attr">immediate</span>:<span class="hljs-literal">true</span> <span class="hljs-comment">// 立即以someObject的当前值触发回调。</span><br>&#125;)<br></code></pre></td></tr></table></figure>

<h4 id="内部原理"><a href="#内部原理" class="headerlink" title="内部原理"></a>内部原理</h4><p>vm.$watch是对Watcher的一种封装，通过Watcher完全可以实现vm.$watch的功能，但它的deep和immediate是Watcher没有的。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-title class_">Vue</span>.<span class="hljs-property">property</span>.<span class="hljs-property">$watch</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">expOrFn, cb, options</span>) &#123;<br>    <span class="hljs-keyword">const</span> vm = <span class="hljs-variable language_">this</span><br>    options = options || &#123;&#125;<br>    <span class="hljs-keyword">const</span> watcher = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Watcher</span>(vm, expOfFn, cb, options)<br>    <span class="hljs-keyword">if</span>(options.<span class="hljs-property">immediate</span>) &#123;<br>        cb.<span class="hljs-title function_">call</span>(vm, watcher)<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">unwatchFn</span>(<span class="hljs-params"></span>) &#123;<br>        watcher.<span class="hljs-title function_">teardown</span>()<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>expOrFn是支持函数的，而之前介绍Watcher时没有添加这部分，需要对Watcher简单修改。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Watcher</span> &#123;<br>    <span class="hljs-title function_">constructor</span>(<span class="hljs-params">vm, expOrFn, cb</span>) &#123;<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">vm</span> = vm<br>        <br>        <span class="hljs-comment">//修改</span><br>        <span class="hljs-keyword">if</span>(<span class="hljs-keyword">typeof</span> expOrFn === <span class="hljs-string">&#x27;function&#x27;</span>) &#123;<br>            <span class="hljs-variable language_">this</span>.<span class="hljs-property">getter</span> = expOrFn<br>        &#125; <span class="hljs-keyword">else</span> &#123;<br>            <span class="hljs-variable language_">this</span>.<span class="hljs-property">getter</span> = <span class="hljs-title function_">parsePath</span>(expOrFn)<br>        &#125;<br>        <br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">cb</span> = cb<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> = <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">get</span>()<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>如果expOrFn是函数，将它直接赋给getter，如果不是，则用parsePath读取keypath中的数据，keypath是属性路径，例如a.b.c.d就代表从vm.a.b.c.d中读取数据。</p>
<p>而expOrFn是函数时，不止可以动态返回数据，其中读取的数据也都会被Watcher观察。当expOrFn是字符串类型的keypath时，Watcher会读取它指向的数据并观察数据的变化。而expOrFn是函数时，Watcher会同时观察expOrFn函数中读取的所有Vue实例上的响应式数据。</p>
<p>执行new Watcher后，代码会判断用户是否用了immediate参数，使用了则立即执行一次cb。</p>
<p>最后返回一个函数unwatcheFn，它的作用是取消观察数据。用户执行它时，实际上是执行了watcher.teardown()来取消观察数据，其本质是把watcher实例从当前正在观察的状态的依赖列表中移除。</p>
<p>现在需要实现watcher中的teardown方法，来实现unwatch功能。</p>
<p>首先需要在Watcher中记录自己都订阅了谁，当Watcher不想继续订阅时，循环自己记录的列表来通知他们将自己从他们的依赖列表中移除。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Watcher</span> &#123;<br>    <span class="hljs-title function_">constructor</span>(<span class="hljs-params">vm, expOrFn, cb</span>) &#123;<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">vm</span>  = vm<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">deps</span> = []<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">depsIds</span>= <span class="hljs-keyword">new</span> <span class="hljs-title class_">Set</span>()<br>        ……<br>    &#125;<br>    <br>    ……<br>    <br>    <span class="hljs-title function_">addDep</span>(<span class="hljs-params">dep</span>) &#123;<br>        <span class="hljs-keyword">const</span> id = dep.<span class="hljs-property">id</span><br>        <span class="hljs-keyword">if</span>(!<span class="hljs-variable language_">this</span>.<span class="hljs-property">depIds</span>.<span class="hljs-title function_">has</span>(id)) &#123;<br>            <span class="hljs-variable language_">this</span>.<span class="hljs-property">depIds</span>.<span class="hljs-title function_">add</span>(id)<br>            <span class="hljs-variable language_">this</span>.<span class="hljs-property">deps</span>.<span class="hljs-title function_">push</span>(dep)<br>            dep.<span class="hljs-title function_">addSub</span>(<span class="hljs-variable language_">this</span>)<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>上述代码中，用depIds判断当前Watcher是否订阅了Dep，不会发生重复订阅。</p>
<p>接着执行this.depIds.add来记录当前Watcher已经订阅了这个Dep。然后执行this.deps.push(dep)记录自己订阅了那些Dep。最后触发dep.addSub(this)将自己订阅到Dep中。</p>
<p>Watcher中新增了addDep方法后，Dep中收集依赖的逻辑也需要改变：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> uid = <span class="hljs-number">0</span><br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Dep</span> &#123;<br>    <span class="hljs-title function_">constructor</span>(<span class="hljs-params"></span>) &#123;<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">id</span> = uid++<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">subs</span> = []<br>    &#125;<br>    <br>    ……<br>    <br>    <span class="hljs-title function_">depend</span>(<span class="hljs-params"></span>) &#123;<br>        <span class="hljs-keyword">if</span>(<span class="hljs-variable language_">window</span>.<span class="hljs-property">target</span>) &#123;<br>            <span class="hljs-variable language_">window</span>.<span class="hljs-property">target</span>.<span class="hljs-title function_">addDep</span>(<span class="hljs-variable language_">this</span>)<br>        &#125;<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<p>Dep会记录数据发生变化的时候，需要通知哪些Watcher，而Watcher中也记录了自己会被哪些Dep通知，是多对多的关系。</p>
<p>在Watcher中记录了自己都订阅了那些Dep后，可以在Watcher中增加teardown方法来通知订阅的Dep，让他们把自己从依赖中移除：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-title function_">teardown</span>(<span class="hljs-params"></span>) &#123;<br>    <span class="hljs-keyword">let</span> i = <span class="hljs-variable language_">this</span>.<span class="hljs-property">deps</span>.<span class="hljs-property">length</span><br>    <span class="hljs-keyword">while</span>(i--) &#123;<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">deps</span>[i].<span class="hljs-title function_">removeSub</span>(<span class="hljs-variable language_">this</span>)<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Dep</span> &#123;<br>    ……<br>    <br>    <span class="hljs-title function_">removeSub</span>(<span class="hljs-params">sub</span>) &#123;<br>        <span class="hljs-keyword">const</span> index = <span class="hljs-variable language_">this</span>.<span class="hljs-property">subs</span>.<span class="hljs-title function_">indexOf</span>(sub)<br>        <span class="hljs-keyword">if</span>(index &gt; -<span class="hljs-number">1</span>) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">subs</span>.<span class="hljs-title function_">splice</span>(index, <span class="hljs-number">1</span>)<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="deep参数实现原理"><a href="#deep参数实现原理" class="headerlink" title="deep参数实现原理"></a>deep参数实现原理</h4><p>deep的 作用是监听它及其子对象的数据，其实就是除了要触发当前被监听数据的收集依赖逻辑外，还要把当前监听值在内的所有子值都触发一遍收集依赖逻辑。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Watcher</span> &#123;<br>    <span class="hljs-title function_">constructor</span>(<span class="hljs-params">vm, expOrFn, cb, options</span>) &#123;<br>        <span class="hljs-variable language_">this</span>.<span class="hljs-property">vm</span> = vm<br>        <span class="hljs-comment">// 新增</span><br>        <span class="hljs-keyword">if</span>(options) &#123;<br>            <span class="hljs-variable language_">this</span>.<span class="hljs-property">deep</span> = !!options.<span class="hljs-property">deep</span><br>        &#125; <span class="hljs-keyword">else</span> &#123;<br>            <span class="hljs-variable language_">this</span>.<span class="hljs-property">deep</span> = <span class="hljs-literal">false</span><br>        &#125;<br>        <br>        ……<br>    &#125;<br>    <br>    <span class="hljs-title function_">get</span>(<span class="hljs-params"></span>) &#123;<br>        <span class="hljs-variable language_">window</span>.<span class="hljs-property">target</span> = <span class="hljs-variable language_">this</span><br>        <span class="hljs-keyword">let</span> value = <span class="hljs-variable language_">this</span>.<span class="hljs-property">getter</span>.<span class="hljs-title function_">call</span>(vm, vm)<br>        <br>        <span class="hljs-comment">//新增</span><br>        <span class="hljs-keyword">if</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">deep</span>) &#123;<br>            <span class="hljs-title function_">traverse</span>(value)<br>        &#125;<br>        windwo.<span class="hljs-property">target</span> = <span class="hljs-literal">undefined</span><br>        <span class="hljs-keyword">return</span> value<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>如果使用了deep参数，则在target = undefined前调用traverse来处理deep的逻辑。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> seenObjects = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Set</span>()<br><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">traverse</span>(<span class="hljs-params">value</span>) &#123;<br>    <span class="hljs-title function_">_traverse</span>(val, seenObjects)<br>    seenObjects.<span class="hljs-title function_">clear</span>()<br>&#125;<br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">_traverse</span>(<span class="hljs-params">val, seen</span>) &#123;<br>    <span class="hljs-keyword">let</span> i , keys<br>    <span class="hljs-keyword">const</span> isA = <span class="hljs-title class_">Array</span>.<span class="hljs-title function_">isArray</span>(val)<br>    <span class="hljs-keyword">if</span>( (!isA &amp;&amp; !<span class="hljs-title function_">isObject</span>(val)) || (<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">isFrozen</span>(val)) ) &#123;<br>        <span class="hljs-keyword">return</span><br>    &#125;<br>    <br>    <span class="hljs-keyword">if</span>(val.<span class="hljs-property">__ob__</span>) &#123;<br>        <span class="hljs-keyword">const</span> depId = val.<span class="hljs-property">__ob__</span>.<span class="hljs-property">dep</span>.<span class="hljs-property">id</span><br>        <span class="hljs-keyword">if</span>(seen.<span class="hljs-title function_">has</span>(depId)) &#123;<br>            <span class="hljs-keyword">return</span><br>        &#125;<br>        seen.<span class="hljs-title function_">add</span>(depId)<br>    &#125;<br>    <span class="hljs-keyword">if</span>(isA) &#123;<br>        i = val.<span class="hljs-property">length</span><br>        <span class="hljs-keyword">while</span>(i--) <span class="hljs-title function_">_traverse</span>(val[i], seen)<br>    &#125; <span class="hljs-keyword">else</span> &#123;<br>        keys =<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">keys</span>(val)<br>        i = keys.<span class="hljs-property">length</span><br>        <span class="hljs-keyword">while</span>(i--) <span class="hljs-title function_">_traverse</span>(val[keys[i]], seen)<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>利用递归来判断子值的类型，数组则直接循环递归调用_traverse，而对象则利用key读取并递归子值，而val[keys[i]]会触发getter，所以要在target = undefined之前触发收集依赖的原因。</p>
<h3 id="vm-set"><a href="#vm-set" class="headerlink" title="vm.$set"></a>vm.$set</h3><h4 id="用法-1"><a href="#用法-1" class="headerlink" title="用法"></a>用法</h4><p><code>vm.$set(target, key, value)</code></p>
<p>在object上设置一个属性，如果object是响应式的，Vue保证属性在创建后也是响应式的，并能够触发视图更新。此方法为了避开Vue不能侦测属性被添加的限制。</p>
<blockquote>
<p>target 不能是Vue实例或Vue实例的根数据对象。</p>
</blockquote>
<p>举个例子来看看</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> vm = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Vue</span>(&#123;<br>    <span class="hljs-attr">el</span>:<span class="hljs-string">&#x27;#el&#x27;</span>,<br>    <span class="hljs-attr">template</span>:<span class="hljs-string">&#x27;#demo-template&#x27;</span>,<br>    <span class="hljs-attr">data</span>:&#123;<br>        obj<br>    &#125;,<br>    <span class="hljs-attr">methods</span>: &#123;<br>        <span class="hljs-title function_">action</span>(<span class="hljs-params"></span>) &#123;<br>            <span class="hljs-variable language_">this</span>.<span class="hljs-property">obj</span>.<span class="hljs-property">name</span> = <span class="hljs-string">&#x27;abc&#x27;</span><br>        &#125;<br>    &#125;<br>&#125;)<br><br></code></pre></td></tr></table></figure>

<p>调用action方法时，会为obj新增一个name属性，但Vue不会得到任何通知，新增的属性也不是响应式的，Vue不知道这个obj新增了属性等同于不知道我们使用了array.length = 0来清空数组一样。而vm.$set就用来解决这类问题。</p>
<h4 id="Array的处理"><a href="#Array的处理" class="headerlink" title="Array的处理"></a>Array的处理</h4><p>首先创建set方法，并规定接收与$set规定的参数一致的三个参数，并对数组进行处理。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">set</span>(<span class="hljs-params">target, key, val</span>) &#123;<br>    <span class="hljs-keyword">if</span>(<span class="hljs-title class_">Array</span>.<span class="hljs-title function_">isArray</span>(target) &amp;&amp; <span class="hljs-title function_">isValidArrayIndex</span>(<span class="hljs-params">key</span>) &#123;<br>        target.<span class="hljs-property">length</span> = <span class="hljs-title class_">Math</span>.<span class="hljs-title function_">max</span>(target.<span class="hljs-property">length</span>, key)<br>        target.<span class="hljs-title function_">splice</span>(key, <span class="hljs-number">1</span>, val)<br>        <span class="hljs-keyword">return</span> val<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>上述代码中，如果target是数组并且key是有效的索引值，就先设置length属性，这样如果我们传的索引值大于length，就需要让target的lenth等于索引。接下来通过splice方法把val设置到target的指定位置，当我们使用splice方法时，数组拦截器会侦测到target变化，自动把新增的val转换成响应式的，最后返回val。</p>
<h4 id="key已经存在target中"><a href="#key已经存在target中" class="headerlink" title="key已经存在target中"></a>key已经存在target中</h4><p>因为key已存在target中，所以它已经被侦测了变化，此时修改数据直接用key和val就好，修改的动作会被侦测到。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">set</span>(<span class="hljs-params">target, key, val</span>) &#123;<br>    <span class="hljs-keyword">if</span>(<span class="hljs-title class_">Array</span>.<span class="hljs-title function_">isArray</span>(target) &amp;&amp; <span class="hljs-title function_">isValidArrayIndex</span>(<span class="hljs-params">key</span>) &#123;<br>        target.<span class="hljs-property">length</span> = <span class="hljs-title class_">Math</span>.<span class="hljs-title function_">max</span>(target.<span class="hljs-property">length</span>, key)<br>        target.<span class="hljs-title function_">splice</span>(key, <span class="hljs-number">1</span>, val)<br>        <span class="hljs-keyword">return</span> val<br>    &#125;<br>    <br>    <span class="hljs-keyword">if</span>(key <span class="hljs-keyword">in</span> target &amp;&amp; !(key <span class="hljs-keyword">in</span> <span class="hljs-title class_">Object</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>)) &#123;<br>        target[key] = val<br>        <span class="hljs-keyword">return</span> val<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="处理新增的属性"><a href="#处理新增的属性" class="headerlink" title="处理新增的属性"></a>处理新增的属性</h4><p>现在处理在target上新增的key：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">set</span>(<span class="hljs-params">target, key, val</span>) &#123;<br>    <span class="hljs-keyword">if</span>(<span class="hljs-title class_">Array</span>.<span class="hljs-title function_">isArray</span>(target) &amp;&amp; <span class="hljs-title function_">isValidArrayIndex</span>(<span class="hljs-params">key</span>) &#123;<br>        target.<span class="hljs-property">length</span> = <span class="hljs-title class_">Math</span>.<span class="hljs-title function_">max</span>(target.<span class="hljs-property">length</span>, key)<br>        target.<span class="hljs-title function_">splice</span>(key, <span class="hljs-number">1</span>, val)<br>        <span class="hljs-keyword">return</span> val<br>    &#125;<br>    <br>    <span class="hljs-keyword">if</span>(key <span class="hljs-keyword">in</span> target &amp;&amp; !(key <span class="hljs-keyword">in</span> <span class="hljs-title class_">Object</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>)) &#123;<br>        target[key] = val<br>        <span class="hljs-keyword">return</span> val<br>    &#125;<br>    <br>    <span class="hljs-comment">// 新增</span><br>    <br>    <span class="hljs-keyword">const</span> ob = target.<span class="hljs-property">__ob__</span><br>    <span class="hljs-keyword">if</span>(target.<span class="hljs-property">_isVue</span> || (ob &amp;&amp; ob.<span class="hljs-property">vmCount</span>)) &#123;<br>        process.<span class="hljs-property">env</span>.<span class="hljs-property">NODE_ENV</span> !== <span class="hljs-string">&#x27;production&#x27;</span> &amp;&amp; <span class="hljs-title function_">warn</span>(<br>            <span class="hljs-string">&#x27;Avoid adding reactive properties to a Vue instance or its root $data&#x27;</span> + <br>            <span class="hljs-string">&#x27;at runtime - declare it upfront in the data option&#x27;</span><br>        )<br>        <span class="hljs-keyword">return</span> val<br>    &#125;<br>    <br>    <span class="hljs-keyword">if</span>(!ob) &#123;<br>        target[key] = val<br>        <span class="hljs-keyword">return</span> val<br>    &#125;<br>    <br>    <span class="hljs-title function_">defineReactive</span>(ob, value, key, val)<br>    ob.<span class="hljs-property">dep</span>.<span class="hljs-title function_">notify</span>()<br>    <span class="hljs-keyword">return</span> val<br>&#125;<br></code></pre></td></tr></table></figure>

<p>上述代码，首先获取了target的__ob__属性，然后处理边界条件即“target不能是Vue实例或Vue实例的跟数据对象”和target不是响应式的情况。若果它身上没有__ob__，则不是响应式的，直接用key和val设置即可。如果前边所有条件都不满足那么说明这是新增的属性，使用defineReactive将新增的属性转成getter/setter即可。</p>
<h3 id="vm-delete"><a href="#vm-delete" class="headerlink" title="vm.$delete"></a>vm.$delete</h3><p>vm.$delete的作用是删除数据中的某个属性，因为Vue2采用Object.defineProperty实现监听，delete关键字删除无法侦测到。</p>
<h4 id="用法-2"><a href="#用法-2" class="headerlink" title="用法"></a>用法</h4><p><code>vm.$delete(target , key)</code></p>
<blockquote>
<p>删除对象的属性，如果对象是响应式的，需要确保删除能更新视图。同样的，目标不能是Vue实例或Vue实例的跟数据对象。</p>
</blockquote>
<h4 id="实现原理"><a href="#实现原理" class="headerlink" title="实现原理"></a>实现原理</h4><p>vm.$delete的实现原理和上述代码类似，删除属性后向依赖发消息。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">del</span>(<span class="hljs-params">target, key</span>) &#123;<br>    <span class="hljs-keyword">if</span>(<span class="hljs-title class_">Array</span>.<span class="hljs-title function_">isArray</span>(target) &amp;&amp; <span class="hljs-title function_">isValidArrayIndex</span>(key)) &#123;<br>        target.<span class="hljs-title function_">splice</span>(key , l)<br>        <span class="hljs-keyword">return</span><br>    &#125;<br>    <br>    <span class="hljs-keyword">const</span> ob = (target).<span class="hljs-property">__ob__</span><br>    <span class="hljs-keyword">if</span>(target.<span class="hljs-property">_isVue</span> || (ob &amp;&amp; ob.<span class="hljs-property">vmCount</span>)) &#123;<br>        process.<span class="hljs-property">env</span>.<span class="hljs-property">NODE_ENV</span> !== <span class="hljs-string">&#x27;production&#x27;</span> &amp;&amp; <span class="hljs-title function_">warn</span>(<br>            <span class="hljs-string">&#x27;Avoid deleting properties on a Vue instance or its root $data&#x27;</span> + <br>            <span class="hljs-string">&#x27;- just set it to null.&#x27;</span><br>        )<br>        <span class="hljs-keyword">return</span><br>    &#125;<br>    <br>    <span class="hljs-keyword">if</span>(!<span class="hljs-title function_">hasOwn</span>(target, key) ) &#123;<br>        <span class="hljs-keyword">return</span><br>    &#125;<br>    <span class="hljs-keyword">delete</span> target[key]<br>    <span class="hljs-keyword">if</span>(!ob) &#123;<br>        <span class="hljs-keyword">return</span><br>    &#125;<br>    ob.<span class="hljs-property">dep</span>.<span class="hljs-title function_">notify</span>()<br>&#125;<br></code></pre></td></tr></table></figure>
                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0/" class="category-chain-item">读书笔记</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/Vue-js/">#Vue.js</a>
      
        <a href="/tags/%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0/">#读书笔记</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>w字总结《深入浅出Vue.js》之变化侦测篇</div>
      <div>https://moewang0321.github.io/2021/12/06/w字总结《深入浅出Vue.js》之变化侦测篇/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Moe Wang</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2021年12月6日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/11/22/w%E5%AD%97%E6%80%BB%E7%BB%93%E3%80%8AJavaScript%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E4%B8%8E%E5%BC%80%E5%8F%91%E5%AE%9E%E8%B7%B5%E3%80%8B%EF%BC%88%E8%AE%BE%E8%AE%A1%E5%8E%9F%E5%88%99%E5%92%8C%E7%BC%96%E7%A8%8B%E6%8A%80%E5%B7%A7%EF%BC%89/" title="w字总结《JavaScript设计模式与开发实践》（设计原则和编程技巧）">
                        <span class="hidden-mobile">w字总结《JavaScript设计模式与开发实践》（设计原则和编程技巧）</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
    <div id="giscus" class="giscus"></div>
    <script type="text/javascript">
      Fluid.utils.loadComments('#giscus', function() {
        var options = {"repo":"moewang0321/moewang0321.github.io","repo-id":"MDEwOlJlcG9zaXRvcnkyMDEyNDI0NTY=","category":"Show and tell","category-id":"DIC_kwDOC_63WM4CUMsH","theme-light":"light_protanopia","theme-dark":"dark_dimmed","mapping":"pathname","reactions-enabled":1,"emit-metadata":1,"input-position":"top","loading":"lazy","lang":"zh-CN"};
        var attributes = {};
        for (let option in options) {
          if (!option.startsWith('theme-')) {
            var key = option.startsWith('data-') ? option : 'data-' + option;
            attributes[key] = options[option];
          }
        }
        var light = 'light_protanopia';
        var dark = 'dark_dimmed';
        window.GiscusThemeLight = light;
        window.GiscusThemeDark = dark;
        attributes['data-theme'] = document.documentElement.getAttribute('data-user-color-scheme') === 'dark' ? dark : light;
        for (let attribute in attributes) {
          var value = attributes[attribute];
          if (value === undefined || value === null || value === '') {
            delete attributes[attribute];
          }
        }
        var s = document.createElement('script');
        s.setAttribute('src', 'https://giscus.app/client.js');
        s.setAttribute('crossorigin', 'anonymous');
        for (let attribute in attributes) {
          s.setAttribute(attribute, attributes[attribute]);
        }
        var ss = document.getElementsByTagName('script');
        var e = ss.length > 0 ? ss[ss.length - 1] : document.head || document.documentElement;
        e.parentNode.insertBefore(s, e.nextSibling);
      });
    </script>
    <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
